package com.luom.fsp.manager.websocket;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.json.JSONUtil;
import com.luom.fsp.config.SpringConfigurator;
import com.luom.fsp.constant.RedisConstant;
import com.luom.fsp.model.dto.other.DashboardResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@ServerEndpoint(value="/ws/dashboard", configurator = SpringConfigurator.class)
@Component
@Slf4j
public class DataWebSocketServer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final Set<DataWebSocketServer> webSocketSet = new ConcurrentHashSet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        log.info("Data WebSocket 连接已打开: {}" ,session.getId());
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(RedisConstant.DASHBOARD_KEY);
        if (!map.isEmpty()) {
            DashboardResult dashboardResult = new DashboardResult();
            dashboardResult.setAfterSales((String) map.get("afterSales"));
            dashboardResult.setPendingShipment((String) map.get("pendingShipment"));
            dashboardResult.setTodayOrders((String) map.get("todayOrders"));
            dashboardResult.setTodaySales((String) map.get("todaySales"));
            DataWebSocketServer.sendMessage(JSONUtil.toJsonStr(dashboardResult));
        }
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("Data WebSocket 连接已关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("Data WebSocket 收到消息: {}" ,message);
        // 可根据需要处理客户端发送的消息
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("Data WebSocket 连接出错: {}" ,error.getMessage());
    }

    // 静态方法，用于推送数据给所有连接的客户端
    public static void sendMessage(String message) {
        for (DataWebSocketServer server : webSocketSet) {
            try {
                String sessionId = server.session.getId();
                log.info("Data WebSocket 推送数据给客户端: {},==============================" ,sessionId);
                server.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 静态方法，用于推送数据给连接的某个客户端
    public static void sendMessage(Long id ,String message) {
        for (DataWebSocketServer server : webSocketSet) {
            try {
                String sessionId = server.session.getId();
                log.info("Data WebSocket 推送数据给客户端: {},==============================" ,sessionId);
                server.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
